import { useTabBar } from "@/store/module/tabBar";

interface IOption {
	url : string;
	success ?: (e : any) => void;
	fail ?: (e : any) => void;
	complete ?: (e : any) => void;
}

/**
 *
 * @param option
 *
 * 重写 uni.switchTab
 *
 * 原理：先切换tab-bar选中idx，然后跳转到index
 *
 * success	Function	否	接口调用成功的回调函数
 *
 * fail	Function	否	接口调用失败的回调函数
 *
 * complete
 */
export default function switchTab(this : any, option : IOption) {
	// 接受参数
	const { url, success, fail, complete } = option;
	// 状态仓库
	const tabBar = useTabBar();
	// 错误提示
	let error : any = "";

	const jumpUrl = `/${url}`;

	try {
		if (tabBar.list.find((item) => item.pagePath === jumpUrl) == undefined) {
			throw new Error(`${url}，页面路径不存在`);
		}

		const idx = tabBar.list.find((item) => item.pagePath === jumpUrl)
			?.idx as number;

		tabBar.setCurrent(idx);

		uni.reLaunch({
			url: "pages/index/index",
		});
	} catch (err) {
		error = err;
	}

	if (success && error == "")
		success({
			code: 0,
			errMsg: "switchTab:ok",
		});

	if (fail)
		fail({
			code: 1,
			errMsg: error == "" ? "switchTab:ok" : `switchTab:${error}`,
		});

	if (complete)
		complete({
			code: 2,
			errMsg: error == "" ? "switchTab:ok" : `switchTab:${error}`,
		});
}